import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_jpush/flutter_jpush.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sy_flutter_alipay/sy_flutter_alipay.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:zhrs/api/api.dart';
import 'package:zhrs/api/app_context.dart';
import 'package:zhrs/mainpage/mainindex.dart';
import 'package:zhrs/pages/face.dart';
import 'package:zhrs/pages/smart_service.dart';
import 'package:zhrs/service/audio_recorder.dart';
import 'package:zhrs/service/nfc_reader.dart';
import 'package:zhrs/utils/StaticContent.dart';
import 'package:zhrs/utils/alert_utils.dart' ;
import 'package:zhrs/utils/windowsSize.dart';

class Testwebview extends StatefulWidget
{


  bool Isinformation;
  String url;
  Testwebview({this.url="http://106.12.180.103/flutter01.html",this.Isinformation=false});
  WebViewController controller;
  @override
  Testwebviews createState()
  {

    return  new Testwebviews();
  }
}

/*class Webviewpage extends StatefulWidget
{

  Webviewpage._internal() {}
  static Webviewpage _instance = Webviewpage._internal();

  factory Webviewpage({String url,bool Isinformation}) {

    return _instance;
  }


  Webviewpages webviewpages;
  bool Isinformation=false;
  String url="http://106.12.180.103/flutter02.html";
  //Webviewpage({this.url="https://www.baidu.com",this.Isinformation=false});

  @override
  Webviewpages createState() {
    webviewpages=new Webviewpages();
    return webviewpages;
  }
}
*/
class Testwebviews extends State<Testwebview>
{

  AudioRec audioRec;

  List<String> hashHex;
  int rangeIndex=0;
  //put 到hash列表
  void putHashHex(String val){
    rangeIndex=(rangeIndex==3?0:rangeIndex);
    hashHex[rangeIndex]=val;
    rangeIndex++;
  }
  Onchange(int index,String url)  {
    // Navigator.push(context, MaterialPageRoute(builder:(context) =>Webviewpage(url:url ,Isinformation: true,)));
    widget.Isinformation=true;
    widget.controller.loadUrl(url);
  }
  @override
  void initState() {
    hashHex=['','',''];
    // TODO: implement initState
    super.initState();
  }
  @override
  Widget build(BuildContext context) {

    windowsSize.mapViewWidth = MediaQuery
        .of(context)
        .size
        .width;
    windowsSize.mapViewHeight = MediaQuery
        .of(context)
        .size
        .height;
    // TODO: implement build
    return   SafeArea(
        child: Scaffold (
            body:  new Container(
                child:  MediaQuery.removePadding(
                    removeTop: true,
                    context: context,
                    child: Container(
                      child: WillPopScope(
                          child:
                          WebView(
                            //  key:item.key,
                            initialUrl: widget.url,
                            javascriptMode: JavascriptMode.unrestricted,
                            onWebViewCreated: (WebViewController webViewController){
                              widget.controller=webViewController;

                            },
                            javascriptChannels: <JavascriptChannel>[
                              _alertJavascriptChannel(context),
                              _appJavascriptChannel(context),
                            ].toSet(),
                            navigationDelegate: (NavigationRequest request)  {
                              if (request.url.startsWith('js://webview/queryUser')) {
                                String userInfo =APP.userModel.loginname;
                                widget.controller.evaluateJavascript(
                                    'getUser("$userInfo")')
                                    ?.then((result) {
                                  print("result:$result");
                                });
                                return NavigationDecision.prevent;
                              }
                              // if(Platform.isAndroid)  SystemChannels.textInput.invokeMethod('TextInput.hide');
                              return NavigationDecision.navigate;
                            },
                            onPageFinished: (String url) {
                              print('Page finished loading: $url');
                            },
                          ),
                          onWillPop: () async{
                            if(widget.Isinformation)
                            {
                              Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                              Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                              dispose();
                              return Future.value(true);
                            }
                            else{
                              var canGoback= await  widget.controller?.canGoBack();
                              if(canGoback){
                                await  widget.controller?.goBack();
                                return Future.value(false);
                              }
                              dispose();
                            }
                            return true;
                          }),
                    )

                )
            )
        )
    );
  }

  @override
  void dispose() {
    print("logout!!!!!!!!!!!");
    clearCache();

    if(audioRec!=null) audioRec.stop();
    super.dispose();
  }
  Future<void> clearCache() async{
    // bottomItems.forEach((item){
    //   item.webViewController.clearCache();
    // });
    widget.controller.clearCache();
  }
  //音频录制
  JavascriptChannel _alertJavascriptChannel(BuildContext context) {
    if(audioRec==null) audioRec=AudioRec();
    return JavascriptChannel(
        name: 'Recorder',
        onMessageReceived: (JavascriptMessage message) {

          switch(message.message){
            case "start":
              audioRec.start(context).then((path){
                widget.controller.evaluateJavascript(
                    'startRecordBackInfo("$path")')
                    ?.then((result) {
                  //print("result:$result");
                });
              });
              break;
            case "isRecording":
              audioRec.isRecording().then((isRecording){
                widget.controller.evaluateJavascript(
                    'isRecordingBackInfo("$isRecording")')
                    ?.then((result) {
                  //print("result:$result");
                });
              });
              break;
            case "stop":
              audioRec.stop().then((path){
                print("path:$path");
                widget.controller.evaluateJavascript(
                    'stopRecordBackInfo("$path")')
                    ?.then((result) {
                  //print("result:$result");
                });
              });
              break;
            default:
          }
        });
  }
  //app
  JavascriptChannel _appJavascriptChannel(BuildContext context) {
    if(audioRec==null) audioRec=AudioRec();
    return JavascriptChannel(
        name: 'App',
        onMessageReceived: (JavascriptMessage message) {
          List<String> mess=message.message.split(":");
          switch(mess[0]){
            case "logout":
              dispose();
              HttpManager.logout(context);
              break;
            case "callScanFace":
              showScanFace(context,mess[1]).then((action){
                widget.controller.evaluateJavascript(
                    'callScanFaceBackInfo("$action")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "pickImage":
              int iq=60;
              if(mess[2]!=null) iq=int.parse(mess[2]);

              ImagePicker.pickImage(source: mess[1]=='1'?ImageSource.camera:ImageSource.gallery,imageQuality:iq).then((image){
                List<int> list= image.readAsBytesSync();

                String base64Str=base64.encode(list);
                widget.controller.evaluateJavascript(
                    'pickImageBackInfo("$base64Str")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "pickImageToHash":
              int iq=60;
              if(mess[2]!=null) iq=int.parse(mess[2]);

              ImagePicker.pickImage(source: mess[1]=='1'?ImageSource.camera:ImageSource.gallery,imageQuality:iq).then((image){
                List<int> list= image.readAsBytesSync( );
                //对文件进行hash
                var digest = sha256.convert(list);
                // 这里其实就是 digest.toString()
                String hexStr= hex.encode(digest.bytes);
                hexStr=hexStr.toUpperCase();
                putHashHex(hexStr);
                widget.controller.evaluateJavascript(
                    'hashImageBackInfo("$hexStr")')
                    ?.then((result) {
                  print("result:$result");
                });

                String base64Str=base64.encode(list);
                widget.controller.evaluateJavascript(
                    'pickImageBackInfo("$base64Str")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "signSbk":
              String str='';
              try {
                hashHex.forEach((val){
                  if(val==''){
                    throw Exception("image$rangeIndex is null");
                  }
                  str=str+val;
                });
                var digest = sha256.convert(hex.decode(str));
                // 这里其实就是 digest.toString()
                String hexStr= hex.encode(digest.bytes);
                hexStr=hexStr.toUpperCase();
                NfcReader().instance.signSbk(hexStr).then((result){
                  widget.controller.evaluateJavascript(
                      'signSbkBackInfo("$result")')
                      ?.then((result) {
                    print("signSbk:$result");
                  });
                });
              } catch (e) {
                print(e);
                widget.controller.evaluateJavascript(
                    'signSbkBackInfo("${e.toString()}")');
              }
              break;
            case "callNFC":

              NfcReader().instance.readSbk().then((result){
                if(result!=null&&result.split(",").length==3){
                  String cardId= NfcReader().instance.resolving(result.split(",")[2]);
                  print("cardId:"+cardId);
                  widget.controller.evaluateJavascript(
                      'callNFCBackInfo("$cardId")')
                      ?.then((result) {
                    print("result:$result");
                  });
                }
              });
              break;
            case "checkNFC":
              NfcReader().instance.checkNFC().then((result){
                widget.controller.evaluateJavascript(
                    'checkNFCBackInfo("$result")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "openSmartService":

              Navigator.push(context, MaterialPageRoute(builder: (context)=>SmartService(mess[1]+':'+mess[2])));
              break;
            case "getCurrentPage":
            // var title=item_now.title;
            // this.controller.evaluateJavascript(
            //     'getCurrentPageBackInfo("$title")')
            //     ?.then((result) {
            //   print("result:$result");
            // });
              break;
            case "hideKeyBoard":
              try {
                if (Platform.isAndroid) SystemChannels.textInput.invokeMethod(
                    'TextInput.hide');
              }catch(e){
                print(e);
              }
              break;
            case "RegistrationID":
              try {

                String RegistrationID=StaticContent.RegistrationID;
                print(RegistrationID);
                if(RegistrationID==null)
                {

                  FlutterJPush.getRegistrationID().then((String regId) async{
                    StaticContent.RegistrationID=regId;
                  });
                }

                widget.controller.evaluateJavascript(
                    'writeRegistrationID("$RegistrationID")')
                    ?.then((result) {
                  print("result:$result");
                });
              }catch(e){
                print(e);
              }
              break;
            case "Alipay":
              try{
                String payInfo=mess[1];
                print(payInfo);

                SyFlutterAlipay.pay(
                    payInfo,
                    urlScheme: '你的ios urlScheme', //前面配置的urlScheme
                    isSandbox: true //是否是沙箱环境，只对android有效
                ).then((res){
                  payInfo=res.toString();
                  print("结果："+ payInfo);
                  widget.controller.evaluateJavascript(
                      'writeAlipay(\'$payInfo\')');
                });
              }
              catch(e){
                print(e);
              }
              break;
            case "Signature":
              try{

                alertSignature(context).then((val){

                  if(val!="null")
                  {
                    widget.controller.evaluateJavascript(
                        'writeSignature(\'$val\')');
                  }

                });
              }
              catch(e){
                print(e);
              }
              break;
            case "Goback":
              try{
                print("进入了");
                if(widget.Isinformation)
                {

                  Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                  Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                  dispose();
                }
                else{

                  if(mess.length>=2)
                  {
                    if(mess[1]=="top")
                    {
                      if(Navigator.pop(context))
                      {
                      }
                      else
                      {
                        Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                      }
                      dispose();
                    }
                  }

                  widget.controller?.canGoBack().then((canGoback)
                  {
                    if(canGoback){
                      widget.controller?.goBack();
                    }
                    else
                    {
                      if(Navigator.pop(context))
                      {
                      }
                      else
                      {
                        Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                      }
                      dispose();
                    }
                  });
                }
              }
              catch(e)
              {
                print(e);
              }
              break;
            default:
          }
        });
  }
}
Future<String> showScanFace(BuildContext context,String title) async{
  var action = await showDialog(context: context,builder: (context){
    return Scaffold(
      body: Container(
        width: 400.0,
        height: 600.0,
        child:FaceScan(title: title,),
      ),
    );
  });
  return action;
}
